#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
 
#include "data_type.h"
#include "alloc.h"
#include "memfunc.h"
#include "basefunc.h"
#include "struct_deal.h"
#include "crypto_func.h"
#include "memdb.h"
#include "message.h"
#include "ex_module.h"
#include "sys_func.h"
#include "file_struct.h"
#include "tcm_constants.h"
#include "tcm_structures.h"
#include "tcmfunc.h"
#include "tcm_cube_struct.h"
#include "tcm_key_manage.h"
#include "tcm_key_desc.h"
#include "tcm_pik_desc.h"
#include "expandstruct_store.h"
#include "tcm_error.h"
// add para lib_include
//
TCM_PUBKEY * pubek;

int expandstruct_store_init(void * sub_proc, void * para)
{
	int ret;

	// add yorself's module init func here
	return 0;
}
int expandstruct_store_start(void * sub_proc, void * para)
{
	int ret;
	void * recv_msg;
	int type;
	int subtype;
	// add yorself's module exec func here

	while(1)
	{
		usleep(time_val.tv_usec);
		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg==NULL)
			continue;
		ret=proc_tcm_expandstruct_store(sub_proc,recv_msg);
	}
	return 0;
}

int proc_tcm_expandstruct_store(void * sub_proc,void * recv_msg)
{
	int ret=0;
	int fd;

	BYTE local_uuid[DIGEST_SIZE];	
	BYTE user_name[DIGEST_SIZE];	
	
	BYTE Buf[DIGEST_SIZE*32];
	BYTE NameBuf[DIGEST_SIZE*4];
	BYTE digest[DIGEST_SIZE];
	UINT32 result;
	RECORD(TCM_KEY_DESC,REMOTE_KEYSET) * remote_keyset;
	RECORD(TCM_KEY_DESC,LOCAL_KEYSET) * local_keyset;
	RECORD(MESSAGE,TYPES) type_pair;
	MSG_EXPAND * msg_expand;
	void * new_msg;
	void * notice_msg;

	printf("begin expandstruct store !\n");

	int typenum=0;

	notice_msg=message_create(TYPE_PAIR(MESSAGE,TYPES),NULL);
	// get remote_keyset from message
	
	ret=message_remove_expand(recv_msg,TYPE_PAIR(TCM_KEY_DESC,REMOTE_KEYSET),&msg_expand);
	if(ret<0)
		return -EINVAL;
	if(msg_expand!=NULL)
	{
		memdb_store(msg_expand->expand,TYPE_PAIR(TCM_KEY_DESC,REMOTE_KEYSET),NULL);
		typenum++;
		type_pair.type=TYPE(TCM_KEY_DESC);
		type_pair.subtype=SUBTYPE(TCM_KEY_DESC,REMOTE_KEYSET);
		message_add_record(notice_msg,&type_pair);
	}

	ret=message_remove_expand(recv_msg,TYPE_PAIR(TCM_KEY_DESC,LOCAL_KEYSET),&msg_expand);
	if(ret<0)
		return -EINVAL;
	if(msg_expand!=NULL)
	{
		memdb_store(msg_expand->expand,TYPE_PAIR(TCM_KEY_DESC,LOCAL_KEYSET),NULL);
		typenum++;
		type_pair.type=TYPE(TCM_KEY_DESC);
		type_pair.subtype=SUBTYPE(TCM_KEY_DESC,LOCAL_KEYSET);
		message_add_record(notice_msg,&type_pair);
	}

	new_msg=recv_msg;
	if(new_msg==NULL)
		return -EINVAL;
	message_set_flag(new_msg,message_get_flag(new_msg) | MSG_FLAG_FOLLOW);
	ret=ex_module_sendmsg(sub_proc,new_msg);
	if(ret<0)
		return ret;

	if(typenum>0)

	ret=ex_module_sendmsg(sub_proc,notice_msg);

	return ret;
}
